package cn.ctodb.web.rest;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.ctodb.app.mail.MailService;
import cn.ctodb.security.SecurityUtils;
import cn.ctodb.web.rest.dto.MailDTO;

@RestController
@RequestMapping("/api/mail")
public class MailResource {

	private final static String EMAIL_FOLDERS = "__EMAIL_FOLDERS__";
	@Resource
	private MailService mailService;

	@RequestMapping(value = "/folders", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<Map<String, String>> getList(HttpSession session) {
		List<Map<String, String>> list = mailService.getFolds(SecurityUtils.getUser());
		session.setAttribute(EMAIL_FOLDERS, list);
		return list;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/inbox/{folder}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<MailDTO> getList(@PathVariable String folder, @RequestParam(name = "page", defaultValue = "1") int page,
			HttpSession session) {
		List<Map<String, String>> list = (List<Map<String, String>>) session.getAttribute(EMAIL_FOLDERS);
		for (Map<String, String> map : list) {
			if (map.get("filter").equals(folder)) {
				folder = map.get("filterName");
				break;
			}
		}
		return mailService.getList(SecurityUtils.getUser(), folder, page, 20);
	}
}
